import tkinter as tk
from tkinter import ttk, messagebox, font
import time
import random

class CapitalBureauApp:
    def __init__(self, root):
        self.root = root
        self.app_start_time = time.time()
        self.root.title("️资本做局器")
        self.root.attributes('-topmost', True)
        self.initial_width = 450
        self.initial_height = 230
        self.BG_COLOR = "#2C3E50"
        self.FG_COLOR = "#ECF0F1"
        self.ACCENT_COLOR_PRIMARY = "#3498DB"
        self.ACCENT_COLOR_SECONDARY = "#E74C3C"
        self.SUCCESS_COLOR = "#2ECC71"
        self.FRAME_BG_COLOR = "#34495E"
        self.BUTTON_TEXT_COLOR = "#FFFFFF"
        self.TRUE_EXIT_BUTTON_COLOR = "#F1C40F"
        self.TRUE_EXIT_BUTTON_ACTIVE_COLOR = "#F39C12"

        self.default_font = font.Font(family="Segoe UI", size=11)
        self.header_font = font.Font(family="Segoe UI", size=18, weight="bold")
        self.button_font = font.Font(family="Segoe UI", size=12, weight="bold")
        self.small_font = font.Font(family="Segoe UI", size=10)
        self.success_font = font.Font(family="Segoe UI", size=14, weight="bold")
        self.wasted_time_font = font.Font(family="Segoe UI", size=16, weight="bold")

        self.root.configure(bg=self.BG_COLOR)
        self.style = ttk.Style()
        self.style.theme_use('clam')

        self.style.configure('.', font=self.default_font, background=self.BG_COLOR, foreground=self.FG_COLOR)
        self.style.configure('TFrame', background=self.FRAME_BG_COLOR, relief='raised', borderwidth=2)
        self.style.configure('ButtonFrame.TFrame', background=self.FRAME_BG_COLOR, relief='flat', borderwidth=0)
        self.style.configure('TLabel', background=self.FRAME_BG_COLOR, foreground=self.FG_COLOR, padding=(5,5))
        self.style.configure('Header.TLabel', font=self.header_font, background=self.FRAME_BG_COLOR, foreground=self.FG_COLOR)
        self.style.configure('Success.TLabel', font=self.success_font, background=self.FRAME_BG_COLOR, foreground=self.SUCCESS_COLOR)
        self.style.configure('WastedTime.TLabel', font=self.wasted_time_font, background=self.FRAME_BG_COLOR, foreground=self.TRUE_EXIT_BUTTON_COLOR)
        self.style.configure('TButton', font=self.button_font, padding=(15, 8, 15, 8), relief="raised", borderwidth=2, foreground=self.BUTTON_TEXT_COLOR)
        self.style.map('TButton', foreground=[('active', self.BUTTON_TEXT_COLOR)])
        self.style.configure('Start.TButton', background=self.ACCENT_COLOR_PRIMARY)
        self.style.map('Start.TButton', background=[('active', '#2980B9'), ('!active', self.ACCENT_COLOR_PRIMARY)])
        self.style.configure('FakeExit.TButton', background=self.ACCENT_COLOR_SECONDARY)
        self.style.map('FakeExit.TButton', background=[('active', '#C0392B'), ('!active', self.ACCENT_COLOR_SECONDARY)])
        self.style.configure('TrueExit.TButton', background=self.TRUE_EXIT_BUTTON_COLOR, foreground="#000000")
        self.style.map('TrueExit.TButton',
                       background=[('active', self.TRUE_EXIT_BUTTON_ACTIVE_COLOR), ('!active', self.TRUE_EXIT_BUTTON_COLOR)],
                       foreground=[('!active', "#000000"), ('active', "#000000")])
        self.style.configure('Horizontal.TProgressbar', troughcolor=self.FRAME_BG_COLOR, background=self.SUCCESS_COLOR, thickness=25, relief='sunken', borderwidth=1)


        self.center_window(self.initial_width, self.initial_height)
        
        # 初始化“惊喜做局”的目标尝试次数
        self.surprise_attempt_target = random.randint(4, 6)
        self.exit_attempts = 0

        self.setup_main_interface() # 会重置 exit_attempts 和 surprise_attempt_target

        # 拦截窗口关闭按钮
        self.root.protocol("WM_DELETE_WINDOW", self.handle_os_window_close)

        self.current_progress_step = 0
        self.total_progress_steps = 100
        duration_sec = 10
        self.progress_delay_ms = int((duration_sec * 1000) / self.total_progress_steps)

    def center_window(self, width, height):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = int((screen_width / 2) - (width / 2))
        y = int((screen_height / 2) - (height / 2))
        self.root.geometry(f"{width}x{height}+{x}+{y}")

    def clear_specific_frames(self):

        if hasattr(self, 'progress_frame') and self.progress_frame.winfo_exists():
            self.progress_frame.pack_forget()
        if hasattr(self, 'main_frame') and self.main_frame.winfo_exists():
            self.main_frame.pack_forget()
        if hasattr(self, 'final_message_display_frame') and self.final_message_display_frame.winfo_exists():
            self.final_message_display_frame.pack_forget()

    def setup_main_interface(self):
        self.exit_attempts = 0 # 重置假退出尝试次数
        self.surprise_attempt_target = random.randint(4, 6) # 随机化“惊喜做局”的目标次数
        self.root.geometry(f"{self.initial_width}x{self.initial_height}")
        self.center_window(self.initial_width, self.initial_height)
        self.clear_specific_frames()

        self.main_frame = ttk.Frame(self.root, padding="30 30 30 30", style='TFrame')
        self.main_frame.pack(expand=True, fill=tk.BOTH)

        self.label = ttk.Label(self.main_frame, text="欢迎使用资本做局器", style='Header.TLabel')
        self.label.pack(pady=(10, 30))

        button_frame = ttk.Frame(self.main_frame, style='ButtonFrame.TFrame')
        button_frame.pack(pady=20)

        self.start_button = ttk.Button(button_frame, text="开始做局", command=self.start_making_bureau, style='Start.TButton', width=12)
        self.start_button.pack(side=tk.LEFT, padx=15)

        self.fake_exit_button = ttk.Button(button_frame, text="不想做局", command=self.attempt_fake_exit, style='FakeExit.TButton', width=12)
        self.fake_exit_button.pack(side=tk.RIGHT, padx=15)

    def start_making_bureau(self):
        self.clear_specific_frames()
        progress_window_width = 450
        progress_window_height = 230
        self.root.geometry(f"{progress_window_width}x{progress_window_height}")
        self.center_window(progress_window_width, progress_window_height)
        self.progress_frame = ttk.Frame(self.root, padding="30", style='TFrame')
        self.progress_frame.pack(expand=True, fill=tk.BOTH)
        self.progress_label_text = tk.StringVar()
        self.progress_label_text.set("吩咐精心策划中，请稍候哈...")
        self.progress_label = ttk.Label(self.progress_frame, textvariable=self.progress_label_text, style='TLabel', font=self.default_font)
        self.progress_label.pack(pady=(20, 10))
        self.progress_bar = ttk.Progressbar(self.progress_frame, orient="horizontal", length=350, mode="determinate", style='Horizontal.TProgressbar')
        self.progress_bar.pack(pady=10)
        self.current_progress_step = 0
        self.run_progress_step_after()

    def run_progress_step_after(self):
        if self.current_progress_step <= self.total_progress_steps:
            self.progress_bar['value'] = self.current_progress_step
            if self.current_progress_step % 10 == 0:
                self.progress_label_text.set(f"策划进度: {self.current_progress_step}% ...")
            self.current_progress_step += 1
            self.root.after(self.progress_delay_ms, self.run_progress_step_after)
        else:
            self.progress_label_text.set("嘿嘿嘿 成功浪费您10秒钟时间")
            self.progress_label.config(style='Success.TLabel')
            self.progress_bar.pack_forget()
            self.true_exit_button = ttk.Button(self.progress_frame, text="那很坏了", command=self.true_exit_procedure, style='TrueExit.TButton', width=20)
            self.true_exit_button.pack(pady=(20, 20))

    def handle_os_window_close(self):
        """处理用户点击操作系统窗口关闭按钮（'X'）的行为"""
        naughty_messages = [
            "我早就猜到你想这么做了，不准退出哦。",
            "嘿，那个叉叉可不是给你点的！想溜？没门儿！",
            "别白费力气啦，这里禁止通行！不如...做个局？",
            "此路不通！这个叉叉是摆设，懂？😉",
            "就知道你会手痒点这里，可惜，这里也归我管！想退出是不可能的！"
        ]
        messagebox.showwarning("嘿！拦住你咯！", random.choice(naughty_messages), icon='warning')

    def attempt_fake_exit(self):
        self.exit_attempts += 1
        current_attempt = self.exit_attempts

        # 检查是否达到随机设定的“惊喜做局”次数
        if current_attempt == self.surprise_attempt_target:
            messagebox.showinfo("出其不意！", f"恭喜你，触发了隐藏剧情！\n(这是您第 {current_attempt} 次尝试退出，真执着！)", icon='info') # 图标改为 info 更“惊喜”
            self.start_making_bureau()
            return # 不再显示后续的假退出消息

        title = "等等！✋"
        msg_to_show = ""

        if current_attempt == 1:
            msg_to_show = "💔 就这么走了吗？项目还没开始呢！"
        elif current_attempt == 2:
            msg_to_show = "😥 我感觉我们之间还有亿点点利润可以挖掘..."
        elif current_attempt == 3:
            msg_to_show = f"😮 第三次了哦？再坚持一下，说不定在第 {self.surprise_attempt_target} 次有好事发生！"
        else:
            generic_messages = [
                "🤔 退出按钮好像...真的坏掉了？要不试试“开始做局”？",
                "🤷‍♂️ 我是一个有原则的做局器，不是你想退就能退的！",
                "你就从了我吧...点“开始做局”才是正道！不然就一直弹这个哦~",
                "再点我可要不客气了！(其实还是很客气的)",
                f"我数到 {self.surprise_attempt_target} ... 你再不“做局”我就...再数一次！"
            ]

            idx_for_generic = current_attempt - 4 
            if idx_for_generic < 0:
                idx_for_generic = 0
            msg_to_show = generic_messages[idx_for_generic % len(generic_messages)]

        messagebox.showwarning(f"{title} (尝试 {current_attempt})", msg_to_show, icon='warning')

    def true_exit_procedure(self):
        end_time = time.time()
        total_wasted_time = end_time - self.app_start_time
        wasted_time_str = "{:.2f}".format(total_wasted_time)
        self.clear_specific_frames()
        self.final_message_display_frame = ttk.Frame(self.root, padding="30", style='TFrame')
        self.final_message_display_frame.pack(expand=True, fill=tk.BOTH)
        final_width = 450
        final_height = 250
        self.root.geometry(f"{final_width}x{final_height}")
        self.center_window(final_width, final_height)
        msg1 = ttk.Label(self.final_message_display_frame, text="其实", style='Header.TLabel', foreground=self.SUCCESS_COLOR)
        msg1.pack(pady=(15,10))
        msg2_text = f"您实际上浪费了宝贵的\n {wasted_time_str} 秒"
        msg2 = ttk.Label(self.final_message_display_frame, text=msg2_text, style='WastedTime.TLabel', justify=tk.CENTER)
        msg2.pack(pady=10)
        msg3 = ttk.Label(self.final_message_display_frame, text="嘿嘿嘿😉", style='TLabel')
        msg3.pack(pady=(10,15))
        self.root.after(6000, self.root.quit)


if __name__ == "__main__":
    root = tk.Tk()
    app = CapitalBureauApp(root)
    root.mainloop()